package com.cd.music.service.impl;

import com.cd.music.dao.DeliveryAddressDao;
import com.cd.music.dao.FCodeDao;
import com.cd.music.dao.OrderDao;
import com.cd.music.dto.OrderDto;
import com.cd.music.dto.ResultBean;
import com.cd.music.dto.UserDto;
import com.cd.music.model.DeliveryAddress;
import com.cd.music.model.FCode;
import com.cd.music.model.Order;
import com.cd.music.service.OrderService;
import com.cd.music.utils.CookieUtil;
import com.cd.music.utils.FormatValidateUtil;
import com.cd.music.utils.IdUtil;
import com.cd.music.utils.StringUtil;
import com.cd.music.utils.TokenUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yxl 余秀良
 * @version 1.0
 * @description: 订单服务实现类
 * @date 2018年03月05日  上午11:17
 * @address: 四川成都
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service(value = "orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private FCodeDao fCodeDao;

    @Resource
    private OrderDao orderDao;

    @Resource
    private DeliveryAddressDao addressDao;

    /**
     * 添加订单
     *
     * @param dto 订单参数
     * @return 返回信息
     * @author yxl 余秀良
     * @version 1.0
     * @description: 添加订单
     * @date 2018年03月05日 上午11:13
     * @address: 四川成都
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public ResultBean insert(OrderDto dto) {
        ResultBean.Builder builder = ResultBean.builder();
        if (dto != null) {
            //收货人联系电话
            String userPhone = dto.getPhone();
            String userName = dto.getUserName();
            String code = dto.getfCode();
            String deliveryAddress = dto.getDeliveryAddress();
            if (!StringUtil.isEmpty(userName) && !StringUtil.isEmpty(userPhone) && FormatValidateUtil.isMobile(userPhone) && !StringUtil.isEmpty(code) && !StringUtil.isEmpty(deliveryAddress)) {
                //验证Ｆ码是否正确
                FCode fCode = new FCode();
                fCode.setValue(code);
                FCode selectFCode = fCodeDao.selectFCode(fCode);
                if (selectFCode != null) {
                    insertOrderAddDataToDatabase(dto, selectFCode, builder);
                } else {
                    builder.success(false).message("Ｆ码不存在").code(200);
                }
            } else {
                builder.success(false).code(400).message("缺少参数");
            }
        } else {
            builder.success(false).code(400).message("缺少参数");
        }
        return builder.build();
    }

    private void insertOrderAddDataToDatabase(OrderDto dto, FCode selectFCode, ResultBean.Builder builder) {
        ResultBean resultBean = CookieUtil.get("token");
        String token = resultBean.getData();
        if (StringUtil.isEmpty(token)) {
            builder.success(false).code(403).message("请登录后再试");
        }
        Map tokenMap = TokenUtil.getParameter(token, Map.class);
        //把用户的收货地址保存到收货详细地址表里面
        DeliveryAddress address = new DeliveryAddress();
        address.setId(IdUtil.getUUID());
        address.setPhone(dto.getPhone());
        address.setDeliveryAddress(dto.getDeliveryAddress());
        address.setProvince(dto.getProvince());
        address.setCity(dto.getCity());
        address.setArea(dto.getArea());
        address.setUserName(dto.getUserName());
        boolean isOk = addressDao.insert(address) > 0;
        if (isOk) {
            //获取id
            String codeId = selectFCode.getId();
            Order order = new Order();
            order.setId(IdUtil.getUUID());
            order.setUserId(tokenMap.get("userId").toString());
            order.setfCodeId(codeId);
            order.setStatus(0);
            order.setIsDelete(false);
            order.setDeliveryAddressId(address.getId());
            order.setGoodsTotal(1);
            order.setGoodsId("1");
            BigDecimal decimal = new BigDecimal(399.00);
            decimal = decimal.setScale(2, BigDecimal.ROUND_HALF_UP);
            order.setOrderAmount(decimal);
            order.setOrderCode(IdUtil.createFCode() + "G");
            isOk = orderDao.insert(order) > 0;
            if (isOk) {
                FCode fCode = new FCode();
                fCode.setIsUse(true);
                fCode.setId(codeId);
                fCode.setValue(dto.getfCode());
                isOk = fCodeDao.updateFCodeStatus(fCode) > 0;
                if (!isOk) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            builder.success(isOk).message(isOk ? "订单生成成功" : "订单生成失败");
        }
    }

    /**
     * 删除订单
     *
     * @param order 订单参数
     * @return 返回信息
     * @author yxl 余秀良
     * @version 1.0
     * @description: 删除订单
     * @date 2018年03月05日 上午11:13
     * @address: 四川成都
     */
    @Override
    public ResultBean delete(Order order) {
        return null;
    }

    /**
     * 修改订单
     *
     * @param dto 订单参数
     * @return 返回信息
     * @author yxl 余秀良
     * @version 1.0
     * @description: 修改订单
     * @date 2018年03月05日 上午11:13
     * @address: 四川成都
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultBean update(OrderDto dto) {
        ResultBean.Builder builder = ResultBean.builder();
        if (dto != null) {
            String payStatus = dto.getPayStatus();
            String userName = dto.getUserName();
            String userPhone = dto.getPhone();
            String deliveryAddress = dto.getDeliveryAddress();
            String id = dto.getId();
            if (!StringUtil.isEmpty(id) && !StringUtil.isEmpty(payStatus) && !StringUtil.isEmpty(userName) && !StringUtil.isEmpty(userPhone) && !StringUtil.isEmpty(deliveryAddress)) {
                dto.setOrderId(id);
                adminUpdateOrderUpdateDatabase(dto, builder);
            } else {
                builder.success(false).message("请检查信息是否填写完整");
            }
        }
        return builder.build();
    }

    /**
     * 管理员修改订单的时候修改数据的方法
     *
     * @param dto     　参数
     * @param builder Builder
     */
    private void adminUpdateOrderUpdateDatabase(OrderDto dto, ResultBean.Builder builder) {
        String payStatus = dto.getPayStatus();
        String fCode = dto.getfCode();
        FCode code = new FCode();
        code.setValue(fCode);
        Order order = new Order();
        order.setId(dto.getOrderId());
        Order order1 = orderDao.selectOrderInfo(order);
        if (order1 != null) {
            //修改订单表数据
            order = new Order();
            order.setStatus(getStatusByPayStatus(payStatus));
            order.setId(dto.getOrderId());
            order.setIsDelete(false);
            boolean isOK = orderDao.update(order) > 0;
            if (isOK) {
                dto.setAddressId(order1.getDeliveryAddressId());
                //修改收货地址表数据
                updateDeliveryAddressData(dto, builder);
            }
        }
    }

    /**
     * 修改收货地址的数据
     *
     * @param dto     　参数
     * @param builder 　Builder
     */
    private void updateDeliveryAddressData(OrderDto dto, ResultBean.Builder builder) {
        //修改收货地址表数据
        DeliveryAddress address = new DeliveryAddress();
        address.setUserName(dto.getUserName());
        address.setPhone(dto.getPhone());
        address.setDeliveryAddress(dto.getDeliveryAddress());
        address.setProvince(dto.getProvince());
        address.setId(dto.getAddressId());
        address.setCity(dto.getCity());
        address.setArea(dto.getArea());
        Order order = new Order();
        order.setId(dto.getOrderId());
        address.setId(dto.getAddressId());
        boolean isOK = addressDao.update(address) > 0;
        if (isOK) {
            builder.success(true).message("修改成功");
        } else {
            builder.success(false).message("修改失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * 获取支付状态
     *
     * @param payStatus 　支付说明
     * @return 返回状态
     */
    private int getStatusByPayStatus(String payStatus) {
        int status;
        switch (payStatus) {
            case "未付款":
                status = 0;
                break;
            case "已付款":
                status = 1;
                break;
            case "已发货":
                status = 2;
                break;
            case "已签收":
                status = 3;
                break;
            default:
                status = 0;
                break;
        }
        return status;
    }

    /**
     * 管理员查询订单列表
     *
     * @param dto 订单参数
     * @return 返回信息
     * @author yxl 余秀良
     * @version 1.0
     * @description: 管理员查询订单列表
     * @date 2018年03月05日 上午11:13
     * @address: 四川成都
     */
    @Override
    public ResultBean adminSelect(OrderDto dto) {
        ResultBean.Builder builder = ResultBean.builder();
        if (dto != null) {
            dto.setUserId(null);
            if (dto.getPageIndex() != null && dto.getPageSize() != null) {
                Integer index = dto.getPageIndex();
                Integer pageSize = dto.getPageSize();
                Integer pageIndex = (index <= 0) ? 0 : ((index - 1) * pageSize);
                dto.setPageIndex(pageIndex);
            }
            List<Map> orderList = orderDao.selectOrderList(dto);
            Integer total = orderDao.selectOrderListCount(dto);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("list", orderList);
            map.put("total", total);
            builder.success(true).data(map);
        } else {
            builder.code(400).message("缺少参数").success(false);
        }
        return builder.build();
    }

    /**
     * 普通用户查询订单
     *
     * @param dto 订单参数
     * @return 返回信息
     * @author yxl 余秀良
     * @version 1.0
     * @description: 普通用户查询订单列表
     * @date 2018年03月05日 上午11:13
     * @address: 四川成都
     */
    @Override
    public ResultBean userSelect(OrderDto dto) {
        ResultBean.Builder builder = ResultBean.builder();
        if (dto != null) {
            ResultBean resultBean = CookieUtil.get("token");
            String token = resultBean.getData();
            if (StringUtil.isEmpty(token)) {
                return builder.success(false).code(403).message("请登录后再试").build();
            }
            UserDto userDto = TokenUtil.getParameter(token, UserDto.class);
            dto.setUserId(userDto.getUserId());
            List<Map> orderList = orderDao.selectOrderList(dto);
            Integer total = orderDao.selectOrderListCount(dto);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("list", orderList);
            map.put("total", total);
            builder.success(true).data(map);
        } else {
            builder.code(400).message("缺少参数").success(false);
        }
        return builder.build();
    }
}
